<?php
namespace Moyu\CloudEncrypt;

class Driver
{
    // 当前实例
    private static $_instance;
    // 加密实例
    private static $_instances = [];

    private static $config = [];

    private function __construct()
    {
        return self::$_instance;
    }

    private function __clone()
    {
        throw new CloudEncryptException(CloudEncryptException::ERROR_CLONE,CloudEncryptException::ERROR_CLONE_CODE);
    }

    private function getDriver($driver){
        return self::$_instances[$driver];
    }

    public static function setConfig($config){
        self::$config = $config;
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public static function getInstance($driver){
        if(!array_key_exists($driver, self::$_instances)){
            $class = 'Moyu\\CloudEncrypt\\Driver\\'.ucwords(strtolower($driver)).'Driver';
            if(!class_exists($class)){
                throw new CloudEncryptException(CloudEncryptException::ERROR_DRIVER_NOT_EXIST,CloudEncryptException::ERROR_DRIVER_NOT_EXIST_CODE);
            }
            self::$_instances[$driver] = new $class(self::$config);
        }
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self();
        }
        return self::$_instance->getDriver($driver);
    }

    public static function support($driver){
        $class = 'Moyu\\CloudEncrypt\\Driver\\'.ucwords(strtolower($driver)).'Driver';
        if(!class_exists($class)){
            return false;
        }
        return true;
    }

}
